package com.alex;

import android.content.Context;
import android.util.Log;

import com.anythink.core.api.ATInitMediation;
import com.anythink.core.api.ATSDK;
import com.anythink.core.api.MediationInitCallback;
import com.bytedance.sdk.openadsdk.TTAdConfig;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdManager;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.bytedance.sdk.openadsdk.TTCustomController;
import com.bytedance.sdk.openadsdk.mediation.init.MediationConfig;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

public class AlexGromoreInitManager extends ATInitMediation {

    private static final String TAG = AlexGromoreInitManager.class.getSimpleName();
    private volatile static AlexGromoreInitManager sInstance;
    MediationConfig.Builder mMediationConfigBuilder;//Mediation Config
    TTCustomController ttCustomController;

    private boolean mIsOpenDirectDownload;
    private AtomicBoolean mIsIniting;
    private boolean mHasInit;
    private List<MediationInitCallback> mListeners;
    private final Object mLock = new Object();

    private final String TT_MEDIATION_INIT_MANAGER = "com.anythink.network.toutiao.TTATInitManager";
    private boolean includeCSJMediationAdapter = false;

    public static AlexGromoreInitManager getInstance() {
        if (sInstance == null) {
            synchronized (AlexGromoreInitManager.class) {
                if (sInstance == null) {
                    sInstance = new AlexGromoreInitManager();
                }
            }
        }
        return sInstance;
    }

    private AlexGromoreInitManager() {
        mIsOpenDirectDownload = true;
        mIsIniting = new AtomicBoolean(false);
        initByTTATInitManagerState();
    }

    @Override
    public void initSDK(Context context, Map<String, Object> serviceExtras,
                        MediationInitCallback callback) {
        AlexGromoreUtil.fbPluginRefresh(context, serviceExtras);

        if (includeCSJMediationAdapter) {
            try {
                //获取CSJ InitManager Instance
                Object csjInitManagerInstance = getCSJInitManagerInstance();
                Method initSDKMediationCSJMethod = csjInitManagerInstance.getClass()
                        .getMethod("initSDK", Context.class, Map.class,
                                MediationInitCallback.class);
                initSDKMediationCSJMethod.invoke(csjInitManagerInstance, context, serviceExtras, callback);
                return;
            } catch (Throwable t) {
                if (ATSDK.isNetworkLogDebug()) {
                    t.printStackTrace();
                }
            }
        }

        if (TTAdSdk.isInitSuccess() || mHasInit) {
            if (callback != null) {
                callback.onSuccess();
            }
            return;
        }

        synchronized (mLock) {

            if (mIsIniting.get()) {
                if (callback != null) {
                    mListeners.add(callback);
                }
                return;
            }

            if (mListeners == null) {
                mListeners = new ArrayList<>();
            }

            mIsIniting.set(true);
        }

        final String appId = getStringFromMap(serviceExtras, "app_id");

        if (callback != null) {
            mListeners.add(callback);
        }

        final int[] download;
        if (mIsOpenDirectDownload) {
            download = new int[]{TTAdConstant.NETWORK_STATE_MOBILE, TTAdConstant.NETWORK_STATE_2G, TTAdConstant.NETWORK_STATE_3G, TTAdConstant.NETWORK_STATE_WIFI, TTAdConstant.NETWORK_STATE_4G};
        } else {
            download = new int[]{TTAdConstant.NETWORK_STATE_2G};
        }

        final Context applicationContext = context.getApplicationContext();
        final String appName = context.getPackageManager()
                .getApplicationLabel(context.getApplicationInfo()).toString();

        runOnMainThread(new Runnable() {
            @Override
            public void run() {
                if (ATSDK.isNetworkLogDebug()) {
                    Log.d(TAG,
                            "start init,includeCSJMediationAdapter: " + includeCSJMediationAdapter);
                }
                try {
                    TTAdConfig ttAdConfig = null;
                    TTAdConfig.Builder initBuilder = new TTAdConfig.Builder().appId(appId)
                            .useMediation(true).useTextureView(
                                    true) //Use the TextureView control to play the video. The default is SurfaceView. When there are conflicts in SurfaceView, you can use TextureView
                            .appName(appName).titleBarTheme(TTAdConstant.TITLE_BAR_THEME_DARK)
                            .directDownloadNetworkType(download) //Allow all network downloads
                            .supportMultiProcess(
                                    false); //Whether to support multiple processes, true support

                    if (ATSDK.isNetworkLogDebug()) {
                        initBuilder.debug(true);
                    }

                    if (ttCustomController != null) {
                        initBuilder.customController(ttCustomController);
                    }

                    if (mMediationConfigBuilder != null) {
                        initBuilder.setMediationConfig(mMediationConfigBuilder.build());
                    }

                    TTAdSdk.init(applicationContext, initBuilder.build());
                    TTAdSdk.start(new TTAdSdk.Callback() {
                        @Override
                        public void success() {
                            runOnThreadPool(new Runnable() {
                                @Override
                                public void run() {
                                    mHasInit = true;
                                    callbackResult(true, null, null);
                                }
                            });
                        }

                        @Override
                        public void fail(int errorCode, String errorMsg) {
                            callbackResult(false, errorCode + "", errorMsg);
                        }
                    });
                    //穿山甲56XX版本开始此初始化api标记为废弃
                    /*TTAdSdk.init(applicationContext, initBuilder.build(), new TTAdSdk.InitCallback() {
                        @Override
                        public void success() {
//                                TTAdSdk will call success before isInitSuccess()==true,delay to check isInitSuccess to return callbackResult success

                        }

                        @Override
                        public void fail(int errorCode, String errorMsg) {
                        }
                    });*/

                } catch (Throwable e) {
                    callbackResult(false, "", e.getMessage());
                }
            }
        });
    }


    private void callbackResult(boolean success, String errorCode, String errorMsg) {
        synchronized (mLock) {
            int size = mListeners.size();
            MediationInitCallback initListener;
            for (int i = 0; i < size; i++) {
                initListener = mListeners.get(i);
                if (initListener != null) {
                    if (success) {
                        initListener.onSuccess();
                    } else {
                        initListener.onFail(errorCode + " | " + errorMsg);
                    }
                }
            }
            mListeners.clear();

            mIsIniting.set(false);
        }
    }

    public void setMediationConfigBuilder(MediationConfig.Builder mediationConfigBuilder) {
        this.mMediationConfigBuilder = mediationConfigBuilder;
        if (includeCSJMediationAdapter) {
            try {
                //获取CSJ InitManager Instance
                Object csjInitManagerInstance = getCSJInitManagerInstance();
                Method isMediationCSJMethod = csjInitManagerInstance.getClass()
                        .getMethod("setMediationConfigBuilder", MediationConfig.Builder.class);
                isMediationCSJMethod.invoke(csjInitManagerInstance, mediationConfigBuilder);
            } catch (Throwable t) {
            }
        }
    }

    public void setIsOpenDirectDownload(boolean download) {
        this.mIsOpenDirectDownload = download;
        if (includeCSJMediationAdapter) {
            try {
                //获取CSJ InitManager Instance
                Object csjInitManagerInstance = getCSJInitManagerInstance();
                Method setIsOpenDirectDownloadMediationCSJMethod = csjInitManagerInstance.getClass()
                        .getMethod("setIsOpenDirectDownload", boolean.class);
                setIsOpenDirectDownloadMediationCSJMethod.invoke(csjInitManagerInstance, download);
            } catch (Throwable t) {
            }
        }
    }

    public void setTtCustomController(TTCustomController ttCustomController) {
        this.ttCustomController = ttCustomController;
        if (includeCSJMediationAdapter) {
            try {
                //获取CSJ InitManager Instance
                Object csjInitManagerInstance = getCSJInitManagerInstance();
                Method setTtCustomControllerMediationCSJMethod = csjInitManagerInstance.getClass()
                        .getMethod("setTtCustomController", TTCustomController.class);
                setTtCustomControllerMediationCSJMethod.invoke(csjInitManagerInstance, ttCustomController);
            } catch (Throwable t) {
            }
        }
    }

    @Override
    public String getNetworkName() {
        return "Gromore";
    }

    @Override
    public String getNetworkVersion() {
        try {
            TTAdManager ttAdManager = TTAdSdk.getAdManager();
            return ttAdManager.getSDKVersion();
        } catch (Throwable e) {
            Log.e(TAG, "getNetworkVersion() >>> " + e.getMessage());
        }
        return "";
    }

    @Override
    public String getNetworkSDKClass() {
        return "com.bytedance.sdk.openadsdk.TTAdSdk";
    }

    @Override
    public List getProviderStatus() {
        ArrayList<String> list = new ArrayList<>();
        list.add("com.bytedance.sdk.openadsdk.multipro.TTMultiProvider");
        list.add("com.bytedance.sdk.openadsdk.TTFileProvider");
        return list;
    }


    private void initByTTATInitManagerState() {
        try {
            //获取CSJ InitManager Instance
            Object csjInitManagerInstance = getCSJInitManagerInstance();
            Method isMediationCSJMethod = csjInitManagerInstance.getClass().getMethod("isMediationCSJ");
            // 调用 isMediationCSJ 方法
            Object result = isMediationCSJMethod.invoke(csjInitManagerInstance);
            if (result instanceof Boolean) {
                Boolean isMediationCSJ = (Boolean) result;
                includeCSJMediationAdapter = isMediationCSJ;
            }
        } catch (Throwable t) {
            if (ATSDK.isNetworkLogDebug()) {
                t.printStackTrace();
            }
        }
    }

    private Object getCSJInitManagerInstance(){
        try {
            Class<? extends ATInitMediation> nativeClass = Class.forName(
                    TT_MEDIATION_INIT_MANAGER).asSubclass(ATInitMediation.class);
            final Constructor<?> nativeConstructor = nativeClass.getDeclaredConstructor(
                    (Class[]) null);
            nativeConstructor.setAccessible(true);
            //get TTATInitManager
            ATInitMediation ttInitManagerObj = (ATInitMediation) nativeConstructor.newInstance();
            Method getInstanceCSJMethod = ttInitManagerObj.getClass().getMethod("getInstance");
            //调用 getInstance 方法
            Object csjInitManagerInstance = getInstanceCSJMethod.invoke(ttInitManagerObj);
            return csjInitManagerInstance;
        }catch (Throwable t){
            if (ATSDK.isNetworkLogDebug()) {
                t.printStackTrace();
            }
        }
        return null;
    }
}
